package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.hyphenate.ui.ChatActivity;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.main.ui.MainActivity;
import com.meitianhui.convenitenbuy.module.order.ui.activity.OrderActivity;
import com.meitianhui.convenitenbuy.module.store.adapter.StoreDetailAdapter;
import com.meitianhui.convenitenbuy.module.store.contract.StoreDetailContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarGoods;
import com.meitianhui.convenitenbuy.module.store.model.StoreDetailCount;
import com.meitianhui.convenitenbuy.module.store.model.StoreDetailInfo;
import com.meitianhui.convenitenbuy.module.store.model.StoreDetailMultiItemType;
import com.meitianhui.convenitenbuy.module.store.model.StoreSelectedGood;
import com.meitianhui.convenitenbuy.module.store.model.StoreType;
import com.meitianhui.convenitenbuy.module.store.presenter.StoreDetailPresenter;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.LoadingDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.module.store.model.StoreDetailMultiItemType.ITEM_GOOD;
import static com.meitianhui.convenitenbuy.module.store.model.StoreDetailMultiItemType.ITEM_NO_DATA;

/*
 Created by amy on 2017/11/21.
 */

public class StoreDetailActivity extends BaseToolbarActivity implements StoreDetailContract.View {
    private final String CANCEL_COLLECT = "stores.consumer.favoriteStoreCancel";
    private final String COLLECT = "stores.consumer.favoriteStore";
    private String mStoreId;
    private String mStoreName;
    private String mStoreAddress;
    private RecyclerView mRvStoreDetail;
    private StoreDetailAdapter mAdapter;
    private TextView mTvCollect;
    private TextView mTvCarNumber;
    private String mTime, mRange, mPrice;
    private String mFavoriteFlag;
    private String mPhone;
    private String mPicInfo;
    private  HashMap<String, String> mUrlMap = new HashMap<>();//活动和门头图片的Url
    private List<StoreDetailMultiItemType> multiItemTypes = new ArrayList<>();
    private List<ShopCarGoods> mShopCarGoodsList = new ArrayList<>();
    private LoadingDialog mDialog;
    private String mType = "推荐";
    @Inject
    StoreDetailPresenter presenter;
    private StoreDetailInfo storeDetailInfo;

    @Override
    protected int setView() {
        return R.layout.activity_store_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        setTbMenu(R.mipmap.store_detail_location);
        initView();
        initData();

    }

    private void initView() {
        isEnable(false);
        RxUtils.bindEvents(getViewById(R.id.tv_phone), this);
        RxUtils.bindEvents(getViewById(R.id.tv_message), this);
        mTvCarNumber = getViewById(R.id.tv_card_num);
        mTvCollect = getViewById(R.id.tv_collect);
        RxUtils.bindEvents(mTvCollect, this);
        RxUtils.bindEvents(getViewById(R.id.tv_car), this);
        RxUtils.bindEvents(getViewById(R.id.tv_order), this);
        mRvStoreDetail = getViewById(R.id.rv_store_detail);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.VERTICAL);
        mRvStoreDetail.setLayoutManager(layout);
        ((SimpleItemAnimator)mRvStoreDetail.getItemAnimator()).setSupportsChangeAnimations(false);
        initRecyclerView();
        registerPush();
    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        List<String> data = new ArrayList<>();
        List<StoreType> storeTypeList = new ArrayList<>();
        List<String> mTypeList = new ArrayList<>();
        multiItemTypes.add(new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_BANNER, data));
        multiItemTypes.add(new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_COUNT, "", "", ""));
        multiItemTypes.add(new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_SERVICE, storeTypeList, mStoreAddress, ""));
        multiItemTypes.add(new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_TYPE, mTypeList, null, null, null));
        mAdapter = new StoreDetailAdapter(multiItemTypes);
        mRvStoreDetail.setAdapter(mAdapter);
        adapterInterface();
    }

    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean eventBean) throws Exception {
                if (eventBean.getType() == Constants.EVENT_TYPE_REFRESH) {
                    presenter.getStoreSelectedGood(mStoreId, mType);
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    /**
     * 菜单按钮点击
     */
    @Override
    protected void clickMenu() {
        super.clickMenu();
        Intent intent = new Intent(this,StoreNavigationActivity.class);
        intent.putExtra("storeDetail",storeDetailInfo);
        startActivity(intent);
    }

    private void adapterInterface() {
        mAdapter.setOnClickListener(new StoreDetailAdapter.StoreDetailAdapterOnClickListener() {
            @Override
            public void groupSaleClick() {
                Intent intent = new Intent(StoreDetailActivity.this, GroupSaleActivity.class);
                intent.putExtra("store_id", mStoreId);
                startActivity(intent);
            }

            @Override
            public void favorablePriceClick() {
                Intent intent = new Intent(StoreDetailActivity.this, PreferentialActivityActivity.class);
                intent.putExtra("store_id", mStoreId);
                intent.putExtra("store_name", mStoreName);
                intent.putExtra("store_address",mStoreAddress);
                intent.putExtra("pic_info",mPicInfo);
                intent.putExtra("url_map",mUrlMap);
                startActivity(intent);
            }

            @Override
            public void oneLotteryClick() {
                Intent intent = new Intent(StoreDetailActivity.this, OneLotteryActivity.class);
                intent.putExtra("store_id", mStoreId);
                intent.putExtra("store_name", mStoreName);
                startActivity(intent);
            }

            @Override
            public void typeItemClick(int position, String type) {
                mType = type;
                presenter.getStoreSelectedGood(mStoreId, type);
            }
        });
    }

    private void initData() {
        Intent intent = this.getIntent();
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        mStoreAddress = intent.getStringExtra("store_address");
        setTbTitle(mStoreName);
        mDialog = new LoadingDialog(this);
        presenter.getStoreDetailInfo(mStoreId);
        presenter.getStoreSelectedType(mStoreId);
        presenter.registerEvent();
    }


    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.tv_phone:   //电话
                if (TextUtils.isEmpty(mPhone)) {
                    return;
                }
                presenter.callPhone(mPhone);
                break;
            case R.id.tv_message:   //消息
                if (!InfoProvider.getLoginStatus(this)) {
                    JumpUtil.jumpToLoginActivity(0, StoreDetailActivity.this, 0, "");
                    return;
                }
                presenter.getHyphenateInfo(mStoreId);
                break;
            case R.id.tv_collect:  //收藏
                if (!InfoProvider.getLoginStatus(this)) {
                    JumpUtil.jumpToLoginActivity(0, StoreDetailActivity.this, 0, "");
                    return;
                }
                if (TextUtils.equals(mFavoriteFlag,"Y")) {
                    presenter.operationCollect(mStoreId, CANCEL_COLLECT);
                } else {
                    presenter.operationCollect(mStoreId, COLLECT);
                }

                break;
            case R.id.tv_car:  //购物车
                if (!InfoProvider.getLoginStatus(this)) {
                    JumpUtil.jumpToLoginActivity(0, StoreDetailActivity.this, 0, "");
                    return;
                }
                String num = mTvCarNumber.getText().toString();
                if (TextUtils.isEmpty(num) || "0".equals(num)) {
                    TipUtils.showToast(App.getInstance(), "请添加商品到购物车！", 3);
                    return;
                }
                Intent intent = new Intent(StoreDetailActivity.this, ShopCarActivity.class);
                intent.putExtra("store_name", mStoreName);
                intent.putExtra("store_address", mStoreAddress);
                intent.putExtra("good_list", (Serializable) mShopCarGoodsList);
//                intent.putExtra("amount", s_amount);
//                intent.putExtra("promotion", s_promotion);
                intent.putExtra("store_id", mStoreId);
                startActivity(intent);
                break;
            case R.id.tv_order:  //订单
                if (!InfoProvider.getLoginStatus(this)) {
                    JumpUtil.jumpToLoginActivity(0, StoreDetailActivity.this, 0, MainActivity.CURRENT_FRAGMENT_TAG_MINE);
                    return;
                }
                Intent intentOrder = new Intent(StoreDetailActivity.this, OrderActivity.class);
                intentOrder.putExtra("order_type", 1);
                startActivity(intentOrder);
                break;
        }
    }


    @Override
    protected void onRefreshData() {

    }

    @Override
    public void getStoreDetailInfoSuccess(StoreDetailInfo data) {
        this.storeDetailInfo = data;
        mTime = data.detail.getOpening_time();//营业时间
        mRange = data.detail.getDeliveried_scope();//配送范围
        mPrice = data.detail.getOver_amount();//起送金额
        mPhone = data.detail.getService_tel();
        mFavoriteFlag = TextUtils.isEmpty(data.detail.favorite_flag)?"N":data.detail.favorite_flag;
        mPicInfo = data.detail.getActivity_pic_info();
        mUrlMap = data.doc_url;
        setCollectIcon(mFavoriteFlag);
        presenter.getStoreDetailCount(mStoreId);
    }

    private void setCollectIcon(String favoriteFlag) {
        if (TextUtils.equals(favoriteFlag,"Y")) {
            mTvCollect.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.icon_store_detail_collect_select, 0, 0);
            mTvCollect.setText("已收藏");
            mTvCollect.setTextColor(Color.parseColor("#ff4242"));
        } else {
            mTvCollect.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.icon_store_detail_collect, 0, 0);
            mTvCollect.setText("收藏");
            mTvCollect.setTextColor(Color.parseColor("#666666"));
        }
    }

    @Override
    public void setBanner(List<String> data) {
        multiItemTypes.set(0, new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_BANNER, data));
        mAdapter.notifyItemChanged(StoreDetailMultiItemType.ITEM_BANNER);
    }

    @Override
    public void setService(List<StoreType> data, String desc) {
        multiItemTypes.set(2, new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_SERVICE, data, mStoreAddress, desc));
        mRvStoreDetail.setAdapter(mAdapter);
        mAdapter.notifyItemChanged(StoreDetailMultiItemType.ITEM_BANNER);
    }

    @Override
    public void getStoreSelectTypeSuccess(Map<String, String> data) {
        List<String> mTypeList = new ArrayList<>();
        if (data != null && data.size() > 0) {
            mTypeList.add(mType);
            for (Map.Entry<String, String> entry : data.entrySet()) {
                mTypeList.add(entry.getValue());
            }
            mTypeList.add("全部");
            presenter.getStoreSelectedGood(mStoreId,mType);
        } else {
            if(mDialog!=null){
                mDialog.stopProgressDialog();
            }
            multiItemTypes.add(new StoreDetailMultiItemType(ITEM_NO_DATA));
        }
        multiItemTypes.set(3, new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_TYPE, mTypeList, mPrice, mRange, mTime));
        mAdapter.notifyItemChanged(StoreDetailMultiItemType.ITEM_TYPE);

    }

    @Override
    public void getStoreSelectedGoodSuccess(StoreSelectedGood data) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }
        StoreDetailMultiItemType multiItemType = new StoreDetailMultiItemType(ITEM_GOOD, data);
        if (multiItemTypes.size() > 4) {
            multiItemTypes.set(4, multiItemType);
        } else {
            multiItemTypes.add(4, multiItemType);
        }
        mAdapter.notifyDataSetChanged();
        adapterInterface();
    }

    @Override
    public void getStoreDetailCountSuccess(StoreDetailCount data) {
        multiItemTypes.set(1, new StoreDetailMultiItemType(StoreDetailMultiItemType.ITEM_COUNT, data.getGroup_booking_count(), data.getCoupon_count(), data.getLd_activity_count()));
        mAdapter.notifyItemChanged(StoreDetailMultiItemType.ITEM_COUNT);

    }

    @Override
    public void operationCollectSuccess(String service) {
        if (service.equals(CANCEL_COLLECT)) {
            mTvCollect.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.icon_store_detail_collect, 0, 0);
            mTvCollect.setText("收藏");
            mTvCollect.setTextColor(Color.parseColor("#666666"));
            mFavoriteFlag = "N";
        } else {
            mTvCollect.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.icon_store_detail_collect_select, 0, 0);
            mTvCollect.setText("已收藏");
            mTvCollect.setTextColor(Color.parseColor("#ff4242"));
            mFavoriteFlag = "Y";
        }

    }

    @Override
    public void getHyphenateInfoSuccess(HyphenateInfo data) {
        Intent intent = new Intent(StoreDetailActivity.this, ChatActivity.class);
        intent.putExtra("userId", data.getIm_user_id());
        intent.putExtra("groupName", data.getNickname());
        startActivity(intent);
    }


    @Override
    public void getEventData(int type, int num, List<ShopCarGoods> shopCarGoodsList) {

        if (type == 0) {
            mTvCarNumber.setVisibility(View.VISIBLE);
            mTvCarNumber.setText(num + "");
            mShopCarGoodsList = shopCarGoodsList;
        } else if (type == 1) {
            if (num == 0) {
                mTvCarNumber.setVisibility(View.GONE);
                mTvCarNumber.setText(num + "");
                mShopCarGoodsList.clear();
            } else {
                mTvCarNumber.setVisibility(View.VISIBLE);
                mTvCarNumber.setText(num + "");
                mShopCarGoodsList = shopCarGoodsList;
            }
        }
    }

    @Override
    public void onFail(int code, String msg) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }
        TipUtils.showToast(App.getInstance(),msg);
    }

    @Override
    public void showError(String msg) {

    }


}
